package com.learning.netease.optimize.frontback.session;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.impl.DefaultClaims;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;
import java.util.UUID;

/**
 * ClassName: UserController
 * Description:
 * Date: 2019/1/29 15:52 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@RestController
@RequestMapping("/user")
public class UserController {


    private final JwtTokenProvider jwtTokenProvider = new JwtTokenProvider("12345678");

    /**
     * 请求 Token
     * http://localhost:8080/user/login/Sam/123
     *
     * @param username
     * @param pwd
     * @return
     */
    @RequestMapping("/login/{username}/{pwd}")
    public String login(@PathVariable String username, @PathVariable String pwd) {
        if (Objects.equals("Sam", username) && Objects.equals("123", pwd)) {
            Claims claims = new DefaultClaims();
            claims.put("username", "Sam");
            claims.setId(UUID.randomUUID().toString());

            return jwtTokenProvider.createToken(claims);
        }
        return null;
    }

    /**
     * 访问地址： http://localhost:8080/user/list
     *
     * @return
     */
    @RequestMapping("/list/{token}")
    public Object list(@PathVariable String token) {
        Claims userClaims = jwtTokenProvider.parseToken(token);
        System.out.println("Claims： " + userClaims);

        if (Objects.equals("Sam", userClaims.get("username"))) {
            return "success ！" + System.currentTimeMillis();
        }

        return "error ！" + System.currentTimeMillis();
    }
}
